package ink.metoo.auto.fishpi.chatroom

import ink.metoo.auto.fishpi.chatroom.command.CommandFactory
import org.jline.reader.Candidate
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import org.jline.reader.ParsedLine
import org.jline.reader.impl.DefaultParser
import org.jline.terminal.Terminal
import org.jline.terminal.TerminalBuilder

object Terminals {

    val terminal: Terminal by lazy {
        val terminalThis = TerminalBuilder.builder()
            .system(true)
            .build()
        terminalThis.enterRawMode()
        terminalThis
    }

    val lineReader: LineReader by lazy {
        LineReaderBuilder.builder()
            .terminal(terminal)
            .completer { _: LineReader?, parsedLine: ParsedLine, list: MutableList<Candidate?> ->
                val buffer = parsedLine.line()
                val cursor = parsedLine.cursor()

                // 查找 @ 符号的位置
                val at = '@'
                val atIndex = buffer.lastIndexOf(at, cursor - 1)
                if (atIndex >= 0) {
                    val prefix = buffer.substring(atIndex + 1, cursor)
                    for (candidate in ChatRooms.onlineUsers) {
                        if (candidate.startsWith(prefix)) {
                            // 拼接at符号, 避免补全后at符号丢失
                            list.add(Candidate(at.toString() + candidate))
                        }
                    }
                } else {
                    CommandFactory.commandSelfTexts.forEach {
                        list.add(Candidate(it))
                    }
                }
            }
            .parser(DefaultParser())
            .build()
    }


}